
//{{{ file documentation -------------------------------------------------------

/*!
 * @file main.cpp
 * @brief dicodor main function
 */

//}}} --------------------------------------------------------------------------
//{{{ includes / predeclarations -----------------------------------------------

#include "config.h"
#include "mainwindow.h"
#include "tools.h"

#include <QtCore/QDebug>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QTranslator>
#include <QtCore/QLibraryInfo>
#include <QtCore/QTextCodec>
#include <QtCore/QLocale>
#include <QtSingleApplication>

#include <QtGui/QApplication>
#include <QtGui/QSplashScreen>
#include <QtGui/QTextDocumentWriter>
#include <QtCore/QRegExp>

#include <ctime>

#include "hspell.h"



//}}} --------------------------------------------------------------------------
//{{{ void test () --------------------------------------------------------------

void test ()
{

	if (false)
	{
		QLocale loc;
		qDebug () << loc.toString (123456789);	// "123 456 789"
		QStringList list;

		list << "janvier" << "février" << "mars" << "avril" << "mai" << "juin"
			 << "juillet" << "août" << "septembre" << "octobre" << "novembre" << "décembre";
		qDebug () << Tools::min (list) << Tools::max (list);

		qDebug () << QIcon::themeSearchPaths () << QIcon::themeName ();
	}
}

//}}} --------------------------------------------------------------------------
//{{{ void initDico () ----------------------------------------------------------

void initDico ()
{
	// as somebody said: a souchon's way of life
	// assume
	// optimization will prevent including this part of code in executable
	// but compiler will oblige us to keep it compilable
	// reducing problems reintroducing it

	if (false)
	{
		// **** aspell dump master it | sort > /home/gilles/Bureau/dico_italien.txt

		QFile file ("/home/gilles/Bureau/dico_italien.txt");
		file.open (QIODevice::ReadOnly);
		QString contain (file.readAll ());
		file.close ();
		QStringList list (contain.split ("\n", QString::SkipEmptyParts));
		QStringList result;
		foreach (const QString & word, list)
		{
			QString wd (word);
			int pos = word.indexOf ('/');
			if (pos)
			{
				wd.truncate (pos);
			}
			if (wd.length () > 1)
			{
				result << wd;
			}
		}
		QByteArray data (result.join ("\n").toUtf8 ());
		QFile file2 ("/home/gilles/Bureau/dic_it.txt");
		file2.open (QIODevice::WriteOnly);
		file2.write (data);
		file2.close ();
	}
}

//}}} --------------------------------------------------------------------------
//{{{ bool initDirs () ----------------------------------------------------------

bool initDirs ()
{
	static QString	error (QObject::tr ("Impossible de créer le répertoire %1\nArrêt de l'application."));
	bool			ok = true;
	const QDir		dir;

	if (! dir.mkpath (Config::appWorkPath ()))
	{
		qDebug () << error.arg (Config::appWorkPath ());
		ok = false;
	}

	if (! dir.mkpath (Config::appHomePath ()))
	{
		qDebug () << error.arg (Config::appHomePath ());
		ok = false;
	}

	if (! dir.mkpath (Config::appExportPath ()))
	{
		qDebug () << error.arg (Config::appExportPath ());
		ok = false;
	}

	return ok;
}

//--------------------------------------------------------------------------
/**
 * @brief main
 * @param argc
 * @param argv
 * @return
 */
int main (int argc, char * argv[])
{
	// ****************************
	// * Initialisations importantes *
	// ****************************

	qsrand (time (NULL)); // semence aléatoire

	QApplication::setDesktopSettingsAware (true);
	QApplication::setQuitOnLastWindowClosed (true);
	QApplication::setGraphicsSystem ("raster");

	QtSingleApplication app (argc, argv);
	if (app.sendMessage ("Wake up!")) return 0;


	app.setOrganizationName ("PapaJaac");
	app.setApplicationName (Config::appName ());
	app.setApplicationVersion (Config::appVersion ());
	app.setWindowIcon (Config::appIcon ());

	// dear users, be patient

	QSplashScreen splash (QPixmap (":/images/splash.png"));
	splash.show ();
	app.processEvents ();

	// some codecs

	QTextCodec::setCodecForTr (QTextCodec::codecForName ("UTF-8"));
	QTextCodec::setCodecForCStrings (QTextCodec::codecForName ("UTF-8"));
	QTextCodec::setCodecForLocale (QTextCodec::codecForName ("UTF-8"));

	// pour avoir les menus, les boutons, les boîtes de dialogue
	// dans la langue locale (configurée dans le système)

	QTranslator qtTranslator;
	qtTranslator.load (
				"qt_" + QLocale::system ().name (),
				QLibraryInfo::location (QLibraryInfo::TranslationsPath)
				);
	app.installTranslator (&qtTranslator);

	// pour avoir l'appli localisée

	QTranslator appTranslator;
	appTranslator.load (
				Config::appName () + '_' + QLocale::system ().name (),
				":/i18n/"
				);
	app.installTranslator (&appTranslator);

	// display version

	splash.showMessage	(QObject::tr ("%1 version %2\n")
						 .arg (Config::appName ())
						 .arg (Config::appVersion ()),
						 Qt::AlignBottom | Qt::AlignHCenter,
						 Qt::blue);
	app.processEvents ();

	// init dirs and dico, test

	if (! initDirs ()) return 99;
	initDico ();
	test ();

	// file to open : -o in args

	QStringList arguments (QApplication::arguments ());
	QString documentPath;

	int indexFileName = arguments.indexOf ("-o") + 1;
	if (indexFileName > 0) {
		if (indexFileName < arguments.size ()) {
			const QString & farg (arguments.at (indexFileName));
			if (QFile (farg).exists ()) {
				documentPath = farg;
			}
			else {
				qDebug () << QObject::tr ("Le fichier %1 n'existe pas").arg (farg);
			}
		}
		else {
			qDebug () << QObject::tr ("Usage : %1 -o <fichier à ouvrir>").arg (Config::appName ());
		}
	}


	// window and application execution

	MainWindow window (documentPath);
	app.setActivationWindow (&window);
	splash.finish (&window);
	window.show ();

	int result = app.exec ();

	return result;
}

//}}} --------------------------------------------------------------------------

